/*
 * @Author: fisher
 * @Date: 2024-02-26 21:26:15
 * @LastEditors: fisher luthor-li@qq.com
 * @LastEditTime: 2024-03-08 17:12:33
 * @FilePath: \allback\utils\ueconfig.js
 * @Description:
 */
const fs = require('fs-extra')
const path = require('path')
// const dayjs = require('dayjs')
exports.copysignalling = async config => {
  async function copyAndConfigureServer(src, dest, configChanges) {
    try {
      // 复制源文件夹到目标文件夹
      await fs.copy(src, dest)
      // 指定配置文件路径
      const configPath = path.join(dest, 'config.json') // 根据您的实际配置文件位置来更改路径
      // 读取 JSON 配置文件内容
      const config = await fs.readJson(configPath)
      // 修改配置文件
      Object.assign(config, configChanges)
      // 写回 JSON 配置文件
      await fs.writeJson(configPath, config, { spaces: 2 })
      return `Server copied and configured: ${dest}`
    } catch (err) {
      // 错误处理
      throw new HttpError(err.message, 400)
    }
  }
  try {
    // const portList = ports.split(',')
    const src = path.resolve(
      __dirname,
      '../UESERVER/pixelstream/SignallingWebServer'
    )

    const dest = path.resolve(
      __dirname,
      `../UESERVER/pixelstream/${config.name}`
    )
    let configChanges = {}
    // 根据useHttps添加对应参数
    if (config.useHttps) {
      configChanges.UseHTTPS = config.useHttps
      configChanges.HttpsPort = parseInt(config.port)
      configChanges.HTTPSCertFile = config.httpsCertFile
      configChanges.HTTPSKeyFile = config.httpsKeyFile
    } else {
      configChanges.HttpPort = parseInt(config.port)
    }
    // 根据是否使用中继添加中继参数
    if (config.useRelay) {
      configChanges.peerConnectionOptions = JSON.stringify({
        offerExtmapAllowMixed: false,
        iceServers: [
          {
            urls: [config.stun, config.turn],
            username: config.relayUsername,
            credential: config.relayPassword
          }
        ]
      })
    }
    // 继续添加常规参数
    configChanges.StreamerPort =
      parseInt(config.port) + parseInt(process.env.StreamerPortDeviation)
    configChanges.SFUPort =
      parseInt(config.port) + parseInt(process.env.StreamerPortDeviation) * 2
    configChanges.instanceId = config._id
    configChanges.platformPort = process.env.PORT
    configChanges.platformHost = process.env.HOST
    await copyAndConfigureServer(src, dest, configChanges)
  } catch (err) {
    throw new HttpError('请检查参数是否正确!', 400)
  }
}

/**
 * @description:获取文件夹下.exe文件名，针对于获取ue项目的启动文件
 * @param {*} dirPath
 * @return {*}
 */
function findExeFilesSync(dirPath) {
  try {
    // 同步读取目录中的所有文件和文件夹
    const items = fs.readdirSync(dirPath)

    // 过滤出带.exe的文件名
    const exeFiles = items.find(
      item => path.extname(item).toLowerCase() === '.exe'
    )

    return exeFiles
  } catch (error) {
    throw new HttpError(error.message, 400)
  }
}
exports.generateStartconfig = async configs => {
  try {
    // 指定配置文件路径
    const configPath = path.resolve(
      __dirname,
      '../UESERVER/pixelstream/config.json'
    ) // 根据您的实际配置文件位置来更改路径
    let configChanges = {
      apps: []
    }
    // 获取local nodejs地址
    for (let i = 0, len = configs.length; i < len; i++) {
      // 添加信令服务器配置
      configChanges.apps.push({
        name: `server_${configs[i].id}`,
        script: 'cirrus.js',
        cwd: path.resolve(
          __dirname,
          `../UESERVER/pixelstream/${configs[i].instanceName}`
        ),
        args: ''
      })
      // 添加ue文件运行配置
      // 获取ue exe文件名称
      const exeFiles = findExeFilesSync(configs[i].uePath)
      configChanges.apps.push({
        name: `ue_${configs[i].id}`,
        script: exeFiles,
        cwd: configs[i].uePath,
        args: `-RenderOffscreen -Unattended -AudioMixer -PixelStreamingURL="ws://${configs[i].instanceIp}:${parseInt(configs[i].instancePort) + parseInt(process.env.StreamerPortDeviation)}"`
      })
    }

    // 写回 JSON 配置文件
    await fs.writeJson(configPath, configChanges, { spaces: 2 })
    return configPath
  } catch (err) {
    throw new HttpError(err.message, 400)
  }
}
